<template>
	<div class="app-container">
		<div class="filter-container">
			<el-select v-model="listQuery.sportStateId" placeholder="请选择赛事类型" filterable>
				<el-option :label="item.valueName" :value="item.valueId" v-for="(item,index) in dictData"
					:key="index"></el-option>
			</el-select>

			<el-input v-model="listQuery.city" placeholder="比赛省市" style="width: 200px;" class="filter-item"
				@keyup.enter.native="handleFilter" />
			<!-- 查询条件隐藏与显示 -->
			<span v-show="showQuery">
				<el-select v-model="listQuery.sportDateChar" placeholder="赛事日期区间" filterable>
					<el-option label="一周内" value="a"></el-option>
					<el-option label="一月内" value="b"></el-option>
					<el-option label="三月内" value="c"></el-option>
				</el-select>
				<el-input v-model="listQuery.minAge" placeholder="最小年龄" style="width: 100px;" class="filter-item"
					@keyup.enter.native="handleFilter" />---
				<el-input v-model="listQuery.maxAge" placeholder="最大年龄" style="width: 100px;" class="filter-item"
					@keyup.enter.native="handleFilter" />
			</span>


			<el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
				查询
			</el-button>
			<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
				@click="handleCreate">
				新增
			</el-button>
			<el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
				@click="handleDownload">
				导出
			</el-button>
			<el-checkbox class="filter-item" style="margin-left:15px;" @change="showMoreQuery">
				更多查询条件
			</el-checkbox>
		</div>

		<el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
			style="width: 100%;" @sort-change="sortChange">
			<el-table-column label="ID" prop="id" sortable="custom" align="center" width="60"
				:class-name="getSortClass('id')">
				<template slot-scope="{row}">
					<span>{{ row.id }}</span>
				</template>
			</el-table-column>
			<el-table-column label="所属赛事" width="80px" align="center">
				<template slot-scope="{row}">
					<span style="color:red;">{{ row.sportId }}</span>
				</template>
			</el-table-column>
			<el-table-column label="标题" min-width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.title }}</span>
				</template>
			</el-table-column>

			<el-table-column label="宣传图片" width="80px" align="center">
				<template slot-scope="{row}">
					<span><img :src='row.sportImg' style='width:50px;height:50px;' /></span>
				</template>
			</el-table-column>
			<el-table-column label="赛事日期" width="100px" align="center" prop='sportDate' :formatter='dateFormatter'>
			</el-table-column>

			<el-table-column label="当前状态" width="80px" prop='sportStateId' align="center" :formatter='StateFormatter'>
				<!-- <template slot-scope="{row}">
					<span>{{ row.sportStateId }}</span>
				</template> -->
			</el-table-column>
			<el-table-column label="报名费用" width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.price }}</span>
				</template>
			</el-table-column>

			<el-table-column label="主办方" width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.sponsor }}</span>
				</template>
			</el-table-column>
			<el-table-column label="报名日期时间" width="120px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.entryDate }}</span>
				</template>
			</el-table-column>
			<el-table-column label="具体地点" min-width="80px" align="center">
				<template slot-scope="{row}">
					<span>{{ row.sportAddress }}</span>
				</template>
			</el-table-column>

			<el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
				<template slot-scope="{row,$index}">
					<el-button type="primary" size="mini" @click="handleUpdate(row)">
						编辑
					</el-button>

					<el-button v-if="row.sportStatus!='Y' && row.sportStatus!='X'" size="mini" type="danger"
						@click="handleDelete(row,$index)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
			@pagination="getList" />

		<!-- 抽屉模态框 -->
		<el-drawer :title="dr_title" :visible.sync="dialog" :before-close="handleClose" direction="rtl"
			custom-class="demo-drawer" size="40%">
			<div class="demo-drawer__content">
				<el-form :inline="true" :model="form" ref="form" :rules="rules" class="demo-form-inline">
					<el-form-item v-if='show_id_item' label="编号ID" :label-width="formLabelWidth">
						<el-input v-model="form.id" :readonly='true'></el-input>
					</el-form-item>
					<el-form-item label="赛事标题" :label-width="formLabelWidth" prop="title">
						<el-input v-model="form.title" size="small"></el-input>
					</el-form-item>
					<el-form-item label="赛事日期" :label-width="formLabelWidth" prop="sportDate">
						<el-input v-model="form.sportDate" type='date' size="small" @change='validDate'></el-input>
					</el-form-item>
					<el-form-item label="赛事类型" :label-width="formLabelWidth" prop="sportStateId">
						<el-select v-model="form.sportStateId" placeholder="请选择角色类型" size="small" filterable>
							<el-option :label="item.valueName" :value="item.valueId" v-for="(item,index) in dictData"
								:key="index"></el-option>
							<!-- <el-option label="管理员" value="1"></el-option>
							<el-option label="开发者" value="2"></el-option>
							<el-option label="员工" value="3"></el-option> -->
						</el-select>
					</el-form-item>
					<el-form-item label="举办地点" :label-width="formLabelWidth" prop="sportCity">
						<el-input v-model="form.sportCity" size="small"></el-input>
					</el-form-item>
					<el-form-item label="参赛年龄" :label-width="formLabelWidth" prop="entryAge">
						<el-input v-model="form.entryAge" type='number' size="small" @blur='validAge'></el-input>
					</el-form-item>

					<el-form-item label="赛事状况" :label-width="formLabelWidth" prop="sportStatus">
						<el-select v-model="form.sportStatus" placeholder="请选择状态" size="small">
							<el-option label="启用" value="Y"></el-option>
							<el-option label="禁用" value="N"></el-option>
							<el-option label="延期" value="N"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="参赛备注" :label-width="formLabelWidth">
						<el-input v-model="form.des" type="textarea" size="small"></el-input>
					</el-form-item>
					<el-form-item label="宣传图片" :label-width="formLabelWidth">
						<el-input v-model="form.sportImg"></el-input>
						<input type="file" size="small" name="files" @change="handleUpload" ref="inputer" accept="application/vnd.ms-powerpoint,
													application/vnd.openxmlformats-officedocument.presentationml.presentation, 
													application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, 
													application/pdf">
						<img v-if="picUrl" :src="picUrl" class="avatar" />

						<!-- <el-upload class="avatar-uploader" action="" :show-file-list="false" :on-change="picturePreview"
							:auto-upload="false">
							<img v-if="imageUrl" :src="imageUrl" class="avatar" />
							<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
						<el-button type="warning" class="cancelBtn" v-show="imageUrl"
							@click="cancelUpload">取消图片</el-button>
						<el-button style="margin-left: 10px;" size="small" type="success"
							@click="submitUpload">上传到服务器</el-button> -->
					</el-form-item>


				</el-form>
				<div class="demo-drawer__footer">
					<el-button icon="el-icon-error" @click="cancelForm">取 消</el-button>
					<el-button icon="el-icon-refresh-right" type="warning" @click="resetForm('form')">重置</el-button>
					<el-button icon="el-icon-check" type="success" @click="handleClose('form')"
						:loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
				</div>
			</div>
		</el-drawer>


		<el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
			<el-table :data="pvData" border fit highlight-current-row style="width: 100%">
				<el-table-column prop="key" label="Channel" />
				<el-table-column prop="pv" label="Pv" />
			</el-table>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		fetchList,
		del,
		updateStatus,
		add,
		update,
		uploadImg,
		fetchPv,
		createArticle,
		updateArticle
	} from '@/api/sportDetailApi';

	import {
		fetchDictList
	} from '@/api/dictApi'

	import waves from '@/directive/waves' // waves directive
	import {
		parseTime
	} from '@/utils'

	import {
		getToken
	} from '@/utils/auth'

	import Pagination from '@/components/Pagination' // secondary package based on el-pagination



	export default {
		name: 'ComplexTable',
		components: {
			Pagination
		},
		directives: {
			waves
		},
		filters: {
			statusFilter(status) {
				const statusMap = {
					Y: 'success',
					N: 'danger'
				}
				return statusMap[status]
			},
			typeFilter(type) {
				return calendarTypeKeyValue[type]
			}
		},
		data() {
			return {
				tableKey: 0,
				list: null,
				total: 0,
				listLoading: true,
				listQuery: {
					pageNo: 1,
					pageSize: 10,
					sort: '+id'
				},

				sortOptions: [{
					label: 'ID Ascending',
					key: '+id'
				}, {
					label: 'ID Descending',
					key: '-id'
				}],

				dialogPvVisible: false,
				pvData: [],
				rules: {
					title: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					sportDate: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					sportStateId: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					entryAge: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					sportCity: [{
						required: true,
						message: '必填字段',
						trigger: 'blur'
					}],
					sportStatus: [{
						required: true,
						message: '必填字段',
						trigger: 'change'
					}]
				},
				downloadLoading: false,
				dialog: false,
				loading: false,
				form: {
					id: '',
					title: '',
					sportDate: '',
					sportImg: '',
					sportStateId: '',
					sportCity: '',
					sportStatus: '',
					entryAge: '',
					des: ''
				},
				formLabelWidth: '80px',
				dr_title: '',
				show_id_item: false,
				dictData: [],
				file: "",
				imageUrl: "",
				picUrl: '',
				showQuery: false
			}
		},
		created() {
			this.getList();
			this.getDictList();
		},
		methods: {
			getList() {
				this.listLoading = true
				fetchList(this.listQuery).then(response => {
					console.info('response==>', response)
					this.list = response.data.records;
					this.total = response.data.total;

					// Just to simulate the time of the request
					setTimeout(() => {
						this.listLoading = false
					}, 1.5 * 1000)
				})
			},
			/* 格式状态 */
			statusFormatter(row, column, cellValue, index) {
				return cellValue == 'Y' ? '已启用' : cellValue == 'N' ? '已禁用' : '已延期';
			},
			/* 赛事state格式化 */
			StateFormatter(row, column, cellValue, index) {
				var str = '';
				switch (cellValue) {
					case 0:
						str = '未开始';
						break;
					case 1:
						str = '报名中';
						break;
					case 2:
						str = '比赛中';
						break;
					case 3:
						str = '已结束';
						break;
					case 4:
						str = '已延期';
						break;
					case 4:
						str = '已延期';
						break;
					default:
						str = '未知';
						break;
				}
				return str;
			},

			dateFormatter(row, column, cellValue, index) {
				return cellValue.substring(0, 10);
			},

			handleFilter() {
				this.listQuery.page = 1
				this.getList()
			},
			handleModifyStatus(row, _status) {
				console.info('row=>', row)
				console.info('status=>', _status);
				this.$confirm('此操作将更改编号为' + row.id + '的数据状态, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					updateStatus({
						id: row.id,
						status: _status
					}).then(res => {
						if (res.code == '201') {
							this.$message({
								type: 'success',
								message: res.msg
							});
							this.getList();
						} else {
							this.$message({
								type: 'error',
								message: res.msg
							});
						}

					}).catch(err => {
						this.$message({
							type: 'error',
							message: '操作异常，请联系管理员！'
						});
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			sortChange(data) {
				const {
					prop,
					order
				} = data;
				if (prop === 'id') {
					this.sortByID(order)
				}
			},
			sortByID(order) {
				if (order === 'ascending') {
					this.listQuery.sort = '+id'
				} else {
					this.listQuery.sort = '-id'
				}
				this.handleFilter()
			},
			showMoreQuery() {
				this.showQuery = !this.showQuery;
			},

			resetTemp() {
				this.temp = {
					id: undefined,
					importance: 1,
					remark: '',
					timestamp: new Date(),
					title: '',
					status: 'published',
					type: ''
				}
			},
			handleCreate() {
				this.dr_title = '新增数据';
				this.dialog = true;
				this.show_id_item = false;
				this.clearForm();
				this.getDictList();
			},
			clearForm() {
				this.form = {
					id: '',
					title: '',
					sportDate: '',
					sportImg: '',
					sportStateId: '',
					sportCity: '',
					entryAge: '',
					des: '',
					sportStatus: 'Y'
				}
				this.picUrl = '';
			},

			handleUpdate(row) {
				this.dr_title = '编辑数据';
				this.dialog = true;
				this.show_id_item = true;
				console.info('row=>', row);
				this.clearForm();
				this.form = {
					id: row.id,
					title: row.title,
					sportDate: row.sportDate,
					sportImg: row.sportImg,
					sportStateId: row.sportStateId,
					sportCity: row.sportCity,
					entryAge: row.entryAge,
					des: row.des,
					sportStatus: row.sportStatus,
				};
				this.getDictList();
			},

			handleDelete(row, index) {
				this.$confirm('此操作将永久删除编号为' + row.id + '的数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					del(row.id).then(res => {
						if (res.code == '201') {
							this.$message({
								message: res.msg,
								type: 'success'
							});
						} else {
							this.$message.error(res.msg);
						}
					}).catch(err => {
						console.error(err);
						this.$message.error('操作异常，请联系管理员！');
					})
					//this.list.splice(index, 1)
					this.getList();
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			handleFetchPv(pv) {
				fetchPv(pv).then(response => {
					this.pvData = response.data.pvData
					this.dialogPvVisible = true
				})
			},
			handleDownload() {
				this.downloadLoading = true
				import('@/vendor/Export2Excel').then(excel => {
					const tHeader = ['编号', '标题', '赛事日期', '宣传图片', '当前状态', '举办地点', '参赛年龄', '赛事状况', '备注']
					const filterVal = ['id', 'title', 'sportDate', 'sportImg', 'sportStateId', 'sportCity',
						'entryAge', 'sportStatus', 'des'
					]
					const data = this.formatJson(filterVal)
					excel.export_json_to_excel({
						header: tHeader,
						data,
						filename: 'sport-list'
					})
					this.downloadLoading = false
				})
			},
			formatJson(filterVal) {
				return this.list.map(v => filterVal.map(j => {
					if (j === 'timestamp') {
						return parseTime(v[j])
					} else {
						return v[j]
					}
				}))
			},

			getSortClass: function(key) {
				const sort = this.listQuery.sort
				return sort === `+${key}` ? 'ascending' : 'descending'
			},
			// 字典表中获取对应角色下拉数据
			getDictList() {
				fetchDictList('sport_code').then(res => {
					if (res.code == '200') {
						this.dictData = res.data;
					}
				}).catch(err => {
					this.$message({
						message: res.msg,
						type: 'error'
					});
				})
			},

			handleClose(formName) {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						this.$confirm('确定要提交表单吗？')
							.then(() => {
								this.loading = true;
								if (this.form.id == '') {
									this.insert();
								} else {
									this.edit();
								}
								this.loading = false;
								this.dialog = false;
							})
							.catch((err) => {
								console.log('error submit!!');
							});

					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			cancelForm() {
				this.loading = false;
				this.dialog = false;
				this.$refs['form'].resetFields();
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},

			formatDate(date) {
				let yyyy = date.getFullYear();
				let mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
				let dd = String(date.getDate()).padStart(2, '0');
				let hh = String(date.getHours()).padStart(2, '0');
				let min = String(date.getMinutes()).padStart(2, '0');
				let ss = String(date.getSeconds()).padStart(2, '0');
				return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}`;
			},
			/* 比赛日期验证有效性、合理性 */
			validDate(value) {
				console.info('value==>', value)
				let _localDate = this.formatDate(new Date());
				if (value < _localDate) {
					this.$message.error('输入日期错误：日期必须大于当前日期！');
					this.form.sportDate = ''
				}
			},

			validAge(event) {
				console.info('event==>', event.target.value)
				let _age = event.target.value;
				if (_age < 1 || _age > 70) {
					this.$message.error('输入年龄错误：年龄必须介于1到70之间！');
					this.form.entryAge = '';
				}
			},

			insert() {
				add(this.form).then(res => {
					if (res.code == '201') {
						this.$message({
							message: res.msg,
							type: 'success'
						});
						this.getList();
					} else {
						this.$message.error(res.msg);
					}
				}).catch(err => {
					console.error(err);
					this.$message.error('操作异常，请联系管理员！');
				})
			},
			edit() {
				update(this.form).then(res => {
					if (res.code == '201') {
						this.$message({
							message: res.msg,
							type: 'success'
						});
						this.getList();
					} else {
						this.$message.error(res.msg);
					}
				}).catch(err => {
					console.error(err);
					this.$message.error('操作异常，请联系管理员！');
				})
			},

			handleAvatarSuccess(res, file) {
				this.imageUrl = URL.createObjectURL(file.raw);
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			//onchange:预览图片
			picturePreview(file, fileList) {
				// console.log("fffff", file.raw);
				//预览图片
				if (window.createObjectURL != undefined) {
					this.imageUrl = window.createObjectURL(file.raw);
				} else if (window.URL != undefined) {
					this.imageUrl = window.URL.createObjectURL(file.raw);
				} else if (window.webkitURL != undefined) {
					this.imageUrl = window.webkitURL.createObjectURL(file.raw);
				}
				this.file = file.raw;
			},
			//取消上传
			cancelUpload() {
				this.imageUrl = "";
				this.file = "";
			},
			//文件上传 async这里本来想设置同步，但是怎么也改不了同步，还是异步
			async uploadPic() {
				const formData = new FormData();
				formData.append("file", this.file);
				formData.append("fileType", "IMAGE");
				let picName = new Date().getTime() + "";
				formData.append("picName", picName);

				this.form.picPath = picName;

				uploadImg(formData).then(res => {
					console.log('uploadres==>', res)
				}).catch(err => {
					this.$message.error("上传失败");
				})
				this.imageUrl = "";
			},
			submitUpload() {
				console.log("图片上传");
				this.uploadPic();
			},

			/* 文件上传 */
			handleUpload(e) {
				/* hack判断当前文件是否为空 */
				let files = e.target.files || e.dataTransfer.files;
				if (!files.length) return;

				/* 创建一个form对象 */
				let formData = new FormData();
				formData.append('files', files[0]); // 添加到form对象中
				console.info('res=>', formData);
				console.info('files[0=>', files[0]);

				uploadImg(formData)
					.then(res => {
						console.info('res=>', res);
						this.form.sportImg = res.data;
						this.picUrl = res.data;
					})
					.catch(err => {
						console.info('err=>', err);
					})
			},
		}
	}
</script>

<style scoped>
	.demo-drawer__footer {
		display: flex;
		margin: 0 30px;
	}

	.demo-drawer__footer button {
		flex: 1;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 58px;
		height: 58px;
		border: 1px solid;
		line-height: 58px;
		text-align: center;
	}

	.avatar {
		width: 78px;
		height: 78px;
		display: block;
	}

	.filter-container div {
		margin: 1vw 1vw;
	}
</style>